package cool.goodbai.controller;

import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import cool.goodbai.api.BaseController;
import cool.goodbai.constant.AliOssImgBedConstant;
import cool.goodbai.constant.ApiConstant;
import cool.goodbai.vo.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "Upload")
@CrossOrigin
@RestController()
@RequestMapping(ApiConstant.BASE_API_URL + "/upload/")
public class UploadController extends BaseController implements AliOssImgBedConstant {
    public final static String MESSAGE_COMMIT = "commit";

    @ApiOperation(value = "文件存储", notes = "文件存储")
    @PostMapping("/uploadFile")
    @ResponseBody
    public Response<Map<String, Object>> uploadFile(@RequestParam(value = "file", required = true) MultipartFile file) throws Exception {
        try {
            Map<String, Object> resultMap = new HashMap<String, Object>();
            InputStream inputStream = file.getInputStream();
            // 获取路径和名称
            String fileName = file.getOriginalFilename();
            // 确保不为空
            assert fileName != null;
            fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            OSS ossClient = new OSSClientBuilder().build(END_POINT, ACCESSKEY_ID, ACCESSKEY_SECRET);
            String uuid = IdUtil.simpleUUID(); // 随机生成名称
            String uploadFilePath = FILE_PATH + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + uuid + suffixName;
            // 上传
            ossClient.putObject(BUCKET_NAME, uploadFilePath, inputStream);
            ossClient.shutdown();
            resultMap.put("fileUrl", "https://" + BUCKET_NAME + "." + END_POINT + "/" + uploadFilePath);
            return getSuccessResult(resultMap);
        } catch (Exception e) {
            return getFailResult(404, "文件上传失败");
        }
    }
}
